﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace file_client
{
    public partial class frmFile : Form
    {
        public int id = 0;
        private DBActive file;
        private bool _ReadOnly = true;

        private DBActive.Storage MainFoto;
        protected bool ReadOnly
        {
            get
            {
                return _ReadOnly;
            }

            set
            {
                _ReadOnly = value;
                cmsContext.Enabled = !value;
                txtSurname.ReadOnly = value;
                txtName.ReadOnly = value;
                txtNick.ReadOnly = value;
                txtAddress.ReadOnly = value;
                txtDetection.ReadOnly = value;
                txtSourceInfo.ReadOnly = value;
                rtfNote.ReadOnly = value;
                cmbParty.Enabled = !value;
                cmbRajonNonOfficial.Enabled = !value;
                cmbRajonOfficial.Enabled = !value;
            }
        }

        public frmFile()
        {
            InitializeComponent();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            id = 0;
            file=null;
            Close();
        }

        private void frmFile_Shown(object sender, EventArgs e)
        {
            try
            {
                this.Text = "Досье " + ((id == 0) ? "новое" : ("№ " + id.ToString()));
                if (id == 0) this.file = new DBActive(Properties.Settings.Default.ConnectionString, Properties.Settings.Default.StartFolder);
                else this.file = new DBActive(Properties.Settings.Default.ConnectionString, Properties.Settings.Default.StartFolder, id);
                txtSurname.DataBindings.Add("Text", file, "Surname");
                txtName.DataBindings.Add("Text", file, "Name");
                txtNick.DataBindings.Add("Text", file, "Nick");
                txtAddress.DataBindings.Add("Text", file, "Address");
                txtDetection.DataBindings.Add("Text", file, "Detection");
                txtSourceInfo.DataBindings.Add("Text", file, "Source");
                rtfNote.DataBindings.Add("Text", file, "Note");
                lsbListFoto.Items.Clear();
                cmbParty.Items.Clear();
                cmbParty.SelectedValue = null;
                cmbRajonNonOfficial.Items.Clear();
                cmbRajonOfficial.Items.Clear();
                lsvStorage.Items.Clear();
                lsvReferenceFile.Items.Clear();

                this.ReadOnly = true;
                if (id != 0)
                {
                    // Загружаем фотографию
                    if (file.MainFoto != null && file.MainFoto.id != 0 && file.MainFoto.Reference != "")
                    {
                        string pathfile = Path.Combine(Properties.Settings.Default.StartFolder, file.MainFoto.Reference);
                        if (File.Exists(pathfile))
                        {
                            pcbFoto.Load(pathfile);
                            tltHint.SetToolTip(pcbFoto, file.MainFoto.Note);
                            lsbListFoto.Items.Add(file.MainFoto);
                        }
                        else
                        {
                            MessageBox.Show("Отсутствует файл главной фотографии на сервере");
                        }
                    }

                    imlPreview.Images.Clear();
                    lsvStorage.Items.Clear();
                    for (int i = 0; i < file.Storages.Length; i++)
                    {
                        if (file.Storages[i].isPicture && (!lsbListFoto.Items.Contains(file.Storages[i]))) lsbListFoto.Items.Add(file.Storages[i]);
                        ListViewItem item = lsvStorage.Items.Add(file.Storages[i].Filename);
                        item.SubItems.Add(file.Storages[i].Note);
                        item.Tag = file.Storages[i];
                        if (file.Storages[i].isPicture)
                        {
                            imlPreview.Images.Add(file.Storages[i].Thumbnail);
                            item.ImageIndex = imlPreview.Images.Count - 1;
                        }
                    }

                    // Одна партия
                    if (file.Partys.Count > 0)
                    {
                        cmbParty.Text = file.Partys[0].ToString();
                        cmbParty.SelectedValue = file.Partys[0];
                    }

                    // Телефоны
                    lsbPhone.Items.Clear();
                    foreach (DBActive.Phone item in file.Phones)
                    {
                        lsbPhone.Items.Add(item);
                    }

                    // районы
                    if (file.RajonOfficialValue != null && file.RajonOfficialValue.id != 0)
                    {
                        cmbRajonOfficial.SelectedValue = file.RajonOfficialValue;
                        cmbRajonOfficial.Text = file.RajonOfficialValue.Caption;
                    }

                    if (file.RajonNonOfficialValue != null && file.RajonNonOfficialValue.id != 0)
                    {
                        cmbRajonNonOfficial.SelectedValue = file.RajonNonOfficialValue;
                        cmbRajonNonOfficial.Text = file.RajonNonOfficialValue.Caption;
                    }

                    // Ссылки
                    foreach (int item_id in file.Links)
                    {
                        ListViewItem item = lsvReferenceFile.Items.Add(item_id.ToString());
                        DBActive item_ref = new DBActive(Properties.Settings.Default.ConnectionString, Properties.Settings.Default.StartFolder, item_id);
                        item.Tag = item_ref;
                        item.SubItems.Add(item_ref.Surname);
                        item.SubItems.Add(item_ref.Name);
                        item.SubItems.Add(item_ref.Nick);
                        item.SubItems.Add(item_ref.Address);
                    }

                    // События
                    foreach (DBActive.Action item_ref in file.Actions)
                    {
                        ListViewItem item = lsvActions.Items.Add((item_ref.ActionDate == null) ? "" : item_ref.ActionDate.ToString());
                        item.Tag = item_ref;
                        item.SubItems.Add(item_ref.Theme);
                        item.SubItems.Add(item_ref.Note);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("При открытии этого досье возникла ошибка! Свяжитесь с администратором программы.\n"+ex.Message);
            }
        }

        private void btnEditSave_Click(object sender, EventArgs e)
        {
            if (ReadOnly)
            {
                ReadOnly = false;
                (sender as Button).Text = "Сохранить";
            }
            else
            {
                if (txtSurname.Text == "" && txtName.Text == "" && txtNick.Text == "")
                {
                    MessageBox.Show("Сохранение без указания фамилии, имени или прозвища не разрешено!");
                    txtSurname.Focus();
                    return;
                }
                ReadOnly = true;
                (sender as Button).Text = "Изменить";
                if (cmbParty.Text != "")
                {
                    DBActive.Party party = new DBActive.Party(file, cmbParty.Text);
                }
                if (cmbRajonOfficial.Text != "")
                {
                    DBActive.RajonOfficial rajon = new DBActive.RajonOfficial(file, cmbRajonOfficial.Text);
                    file.RajonOfficialValue = rajon;
                }
                if (cmbRajonNonOfficial.Text != "")
                {
                    DBActive.RajonNonOfficial rajon = new DBActive.RajonNonOfficial(file, cmbRajonNonOfficial.Text);
                    file.RajonNonOfficialValue = rajon;
                }
                file.Save();
                id = file.id;
                this.Text = "Досье № " + id.ToString();
            }
        }

        private void удалитьToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (id == 0) return;
            if (cmsContext.SourceControl.Name == "pcbFoto")
            {
                //if (MessageBox.Show("Внимание! Добавление картинки будет немедленно отражено в базе данных. Желаете продолжить?", "Досье", MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.Cancel)
                //    return;
                pcbFoto.Image = null;
                pcbFoto.Refresh();
                file.MainFoto.Delete();
                tltHint.SetToolTip(pcbFoto, "");
                return;
            }
            if (cmsContext.SourceControl.Name == "lsbPhone" && lsbPhone.SelectedItem != null)
            {
                (lsbPhone.SelectedItem as DBActive.Phone).Delete();
                lsbPhone.Items.RemoveAt(lsbPhone.SelectedIndex);
                return;
            }
            if (cmsContext.SourceControl.Name == "lsvActions")
            {
                if (lsvActions.SelectedItems.Count != 1) return;
                DBActive.Action action = (lsvActions.SelectedItems[0].Tag as DBActive.Action );
                action.Delete();
                return;
            }
            if (cmsContext.SourceControl.Name == "lsvReferenceFile" && lsvReferenceFile.SelectedItems.Count == 1)
            {
                file.DeleteLink((lsvReferenceFile.SelectedItems[0].Tag as DBActive).id);
                lsvReferenceFile.SelectedItems[0].Remove();
                return;
            }
            if (cmsContext.SourceControl.Name == lsvStorage.Name && lsvStorage.SelectedItems.Count == 1)
            {
                (lsvStorage.SelectedItems[0].Tag as DBActive.Storage).Delete();
                lsvStorage.Items.RemoveAt(lsvStorage.SelectedItems[0].Index);
                return;
            }
        }

        private void изменитьToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (id == 0) return;
            if (cmsContext.SourceControl.Name == "pcbFoto")
            {
                //if (MessageBox.Show("Внимание! Добавление картинки будет немедленно отражено в базе данных. Желаете продолжить?", "Досье", MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.Cancel)
                //    return;
                frmStorageEdit form = new frmStorageEdit();
                form.txtFileName.Text = file.MainFoto.Filename;
                form.txtNote.Text = file.MainFoto.Note;
                form.PostDoing += form_PostDoingMainFotoEdit;
                form.ShowDialog();
            }
            if (cmsContext.SourceControl.Name == "lsbPhone" && lsbPhone.SelectedItem!=null)
            {
                frmPhoneItem form = new frmPhoneItem();
                form.Adding = false;
                form.btnOK.Click += frmPhoneItem_btnOK_Click;
                form.txtPhoneNumber.Text = lsbPhone.SelectedItem.ToString();
                form.cmbPhoneCategory.SelectedIndex = (lsbPhone.SelectedItem as DBActive.Phone).Category;
                form.ShowDialog();
                return;
            }
            if (cmsContext.SourceControl.Name == "lsvActions")
            {
                if (lsvActions.SelectedItems.Count != 1) return;
                frmActiveItem form = new frmActiveItem();
                form.Adding = false;
                form.btnOK.Click += frmActiveItem_btnOK_Click;
                if ((lsvActions.SelectedItems[0].Tag as DBActive.Action).ActionDate== null) 
                    form.dtpDateAction.Checked = false;
                else
                {
                    form.dtpDateAction.Checked = true;
                    form.dtpDateAction.Value = (DateTime)(lsvActions.SelectedItems[0].Tag as DBActive.Action).ActionDate;
                }
                form.txtTheme.Text = (lsvActions.SelectedItems[0].Tag as DBActive.Action).Theme;
                form.txtNote.Text = (lsvActions.SelectedItems[0].Tag as DBActive.Action).Note;
                form.ShowDialog();
                return;
            }
            if (cmsContext.SourceControl.Name == lsvStorage.Name && lsvStorage.SelectedItems.Count == 1)
            {
                frmStorageEdit form = new frmStorageEdit();
                DBActive.Storage storage = (lsvStorage.SelectedItems[0].Tag as DBActive.Storage);
                form.txtFileName.Text = storage.Filename;
                form.txtNote.Text = storage.Note;
                form.PostDoing += form_PostDoingStorageEdit;
                form.ShowDialog();
                return;
            }
        }

        private void form_PostDoingMainFotoEdit(object sender, EventArgs e)
        {
            DBActive.Storage _mainfoto = file.MainFoto;
            _mainfoto.Note = ((sender as Button).Parent as frmStorageEdit).txtNote.Text;
            _mainfoto.Filename = ((sender as Button).Parent as frmStorageEdit).txtFileName.Text;
            _mainfoto.Save();
            tltHint.SetToolTip(pcbFoto, _mainfoto.Note);
            ((sender as Button).Parent as frmStorageEdit).PostDoing -= form_PostDoingMainFotoEdit;
        }

        private void добавитьToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                //if (id == 0)
                //{
                //    MessageBox.Show("Прежде чем добавить фотографию необходимо, что бы досье было сохранено");
                //    return;
                //}
                if (cmsContext.SourceControl.Name == "pcbFoto")
                {
                    //if (MessageBox.Show("Внимание! Добавление картинки будет немедленно отражено в базе данных. Желаете продолжить?", "Досье", MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.Cancel)
                    //    return;
                    OpenFileDialog dialog = new OpenFileDialog();
                    dialog.Filter = "Картинка, Фото| *.jpg;*.jpeg;*.bmp;*.png";
                    if (dialog.ShowDialog() != System.Windows.Forms.DialogResult.Cancel)
                    {
                        frmStorageEdit form = new frmStorageEdit();
                        FileInfo fi = new FileInfo(dialog.FileName);
                        form.txtFileName.Text = fi.Name;
                        form.txtNote.Text = "";
                        form.PostDoing += form_PostDoingMainFotoAdd;
                        form.FullFileName = fi.FullName;
                        form.ShowDialog();
                    }
                    return;
                }
                if (cmsContext.SourceControl.Name == "lsbPhone")
                {
                    frmPhoneItem form = new frmPhoneItem();
                    form.Adding = true;
                    form.btnOK.Click += frmPhoneItem_btnOK_Click;
                    form.txtPhoneNumber.Text = "";
                    form.cmbPhoneCategory.SelectedIndex = -1;
                    form.ShowDialog();
                    return;
                }
                if (cmsContext.SourceControl.Name == "lsvActions")
                {
                    frmActiveItem form = new frmActiveItem();
                    form.Adding = true;
                    form.btnOK.Click += frmActiveItem_btnOK_Click;
                    form.dtpDateAction.Checked = false;
                    form.txtTheme.Text = "";
                    form.txtNote.Text = "";
                    form.ShowDialog();
                    return;
                }
                if (cmsContext.SourceControl.Name == "lsvReferenceFile")
                {
                    frmFileItem form = new frmFileItem();
                    form.btnOk.Click += frmFileItembtnOk_Click;
                    form.txtFileNumber.Text = "";
                    form.ShowDialog();
                    return;
                }
                if (cmsContext.SourceControl.Name == lsvStorage.Name)
                {
                    OpenFileDialog dialog = new OpenFileDialog();
                    dialog.Filter = "Все файлы | *.*";
                    dialog.Multiselect = true;
                    if (dialog.ShowDialog() != System.Windows.Forms.DialogResult.Cancel)
                    {
                        if (dialog.FileNames.Length == 1)
                        {
                            frmStorageEdit form = new frmStorageEdit();
                            FileInfo fi = new FileInfo(dialog.FileName);
                            form.txtFileName.Text = fi.Name;
                            form.txtNote.Text = "";
                            form.PostDoing += form_PostDoingStorageAdd;
                            form.FullFileName = fi.FullName;
                            form.ShowDialog();
                        }
                        else
                        {
                            for (int i = 0; i < dialog.FileNames.Length; i++)
                            {
                                FileInfo fi = new FileInfo(dialog.FileNames[i]);
                                DBActive.Storage storage = new DBActive.Storage(file, fi.FullName, "");
                                storage.Filename = fi.Name;
                                storage.Save();
                            }
                            imlPreview.Images.Clear();
                            lsvStorage.Items.Clear();
                            for (int i = 0; i < file.Storages.Length; i++)
                            {
                                if (file.Storages[i].isPicture && (!lsbListFoto.Items.Contains(file.Storages[i]))) lsbListFoto.Items.Add(file.Storages[i]);
                                ListViewItem item = lsvStorage.Items.Add(file.Storages[i].Filename);
                                item.SubItems.Add(file.Storages[i].Note);
                                item.Tag = file.Storages[i];
                                if (file.Storages[i].isPicture)
                                {
                                    imlPreview.Images.Add(file.Storages[i].Thumbnail);
                                    item.ImageIndex = imlPreview.Images.Count - 1;
                                }
                            }
                        }
                    }
                    return;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка при добавлении файла\n" + ex.Message);
            }
        }

        private void frmFileItembtnOk_Click(object sender, EventArgs e)
        {
            frmFileItem form = ((sender as Button).Parent as frmFileItem);
            try
            {
                int item_id = int.Parse(form.txtFileNumber.Text);
                DBActive item_ref = new DBActive(Properties.Settings.Default.ConnectionString, Properties.Settings.Default.StartFolder, item_id);
                ListViewItem item = lsvReferenceFile.Items.Add(item_id.ToString());
                item.Tag = item_ref;
                item.SubItems.Add(item_ref.Surname);
                item.SubItems.Add(item_ref.Name);
                item.SubItems.Add(item_ref.Nick);
                item.SubItems.Add(item_ref.Address);
                file.AddLink(item_id);
            }
            catch
            {
                MessageBox.Show("Невозможно добавить ссылку на это дело. Проверьте правильность ввода или его наличие");
            }
            form.Close();
        }

        void frmActiveItem_btnOK_Click(object sender, EventArgs e)
        {
            frmActiveItem form = ((sender as Button).Parent as frmActiveItem);
            DBActive.Action action = null;
            DateTime? actiondate  =null;
            if (form.dtpDateAction.Checked) actiondate = form.dtpDateAction.Value;
            if (form.Adding)
            {
                action = new DBActive.Action(file, actiondate, form.txtTheme.Text, form.txtNote.Text);
                ListViewItem item = lsvActions.Items.Add("");
                if (form.dtpDateAction.Checked) action.ActionDate = form.dtpDateAction.Value;
                else action.ActionDate = null;
                action.Theme = form.txtTheme.Text;
                action.Note = form.txtNote.Text;
                if (action != null) item.Text = action.ActionDate.ToString();
                item.SubItems.Add(action.Theme);
                item.SubItems.Add(action.Note);
            }
            else if (lsvActions.SelectedItems.Count == 1)
            {
                ListViewItem item = lsvActions.SelectedItems[0];
                action = (item.Tag as DBActive.Action);
                if (form.dtpDateAction.Checked) action.ActionDate = form.dtpDateAction.Value;
                else action.ActionDate = null;
                action.Theme = form.txtTheme.Text;
                action.Note = form.txtNote.Text;
                if (action.ActionDate != null) item.Text = action.ActionDate.ToString();
                else item.Text = "";
                item.SubItems[1].Text=action.Theme;
                item.SubItems[2].Text=action.Note;
            }
            if (action != null) action.Save();
            form.Close();
        }

        private void frmPhoneItem_btnOK_Click(object sender, EventArgs e)
        {
            frmPhoneItem form = ((sender as Button).Parent as frmPhoneItem);
            if (form.txtPhoneNumber.Text!="")
                if (form.Adding)
                {
                    DBActive.Phone phone = new DBActive.Phone(file, form.txtPhoneNumber.Text, form.cmbPhoneCategory.SelectedIndex);
                    lsbPhone.Items.Add(phone);
                    phone.Save();
                }
                else
                {
                    if (lsbPhone.SelectedItem == null) return; 
                    DBActive.Phone phone = (lsbPhone.SelectedItem as DBActive.Phone);
                    phone.PhoneNumber = form.txtPhoneNumber.Text;
                    phone.Category = form.cmbPhoneCategory.SelectedIndex;
                    phone.Save();
                    lsbPhone.Items.Clear();
                    foreach (DBActive.Phone item in file.Phones)
	                {
		                lsbPhone.Items.Add(item);
	                }
                }
            form.Close();
        }
        private void form_PostDoingMainFotoAdd(object sender, EventArgs e)
        {
            MainFoto = new DBActive.Storage(file, 
                ((sender as Button).Parent as frmStorageEdit).FullFileName,
                ((sender as Button).Parent as frmStorageEdit).txtNote.Text);
            MainFoto.Filename = ((sender as Button).Parent as frmStorageEdit).txtFileName.Text;
            MainFoto.Save();
            file.MainFoto = MainFoto;
            pcbFoto.Load(Path.Combine(Properties.Settings.Default.StartFolder, MainFoto.Reference));
            tltHint.SetToolTip(pcbFoto, file.MainFoto.Note);
            lsbListFoto.Items.Clear();
            lsbListFoto.Items.Add(file.MainFoto);
            imlPreview.Images.Clear();
            lsvStorage.Items.Clear();
            for (int i = 0; i < file.Storages.Length; i++)
            {
                if (file.Storages[i].isPicture && (!lsbListFoto.Items.Contains(file.Storages[i]))) lsbListFoto.Items.Add(file.Storages[i]);
                ListViewItem item = lsvStorage.Items.Add(file.Storages[i].Filename);
                item.SubItems.Add(file.Storages[i].Note);
                item.Tag = file.Storages[i];
                if (file.Storages[i].isPicture)
                {
                    imlPreview.Images.Add(file.Storages[i].Thumbnail);
                    item.ImageIndex = imlPreview.Images.Count - 1;
                }
            }
            ((sender as Button).Parent as frmStorageEdit).PostDoing -= form_PostDoingMainFotoAdd;
        }

        private void lsbListFoto_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lsbListFoto.SelectedItem == null) return;
            DBActive.Storage _currentitem = (lsbListFoto.SelectedItem as DBActive.Storage);
            pcbFoto.Load(Path.Combine(Properties.Settings.Default.StartFolder, _currentitem.Reference));
            tltHint.SetToolTip(pcbFoto, _currentitem.Note);
        }

        private void lsbPhone_DoubleClick(object sender, EventArgs e)
        {
            if (ReadOnly) return;
            if (lsbPhone.SelectedItem == null) return;
            frmPhoneItem form = new frmPhoneItem();
            form.Adding = false;
            form.btnOK.Click += frmPhoneItem_btnOK_Click;
            form.txtPhoneNumber.Text = lsbPhone.SelectedItem.ToString();
            DBActive.Phone phone = (lsbPhone.SelectedItem as DBActive.Phone);
            form.cmbPhoneCategory.SelectedIndex = phone.Category;
            form.ShowDialog();
            return;
        }

        private void pcbFoto_DoubleClick(object sender, EventArgs e)
        {
            if (file == null || file.MainFoto == null || file.MainFoto.id == 0 || file.MainFoto.Reference == "") return;
            string path = Path.Combine(Properties.Settings.Default.StartFolder, file.MainFoto.Reference);
            if (File.Exists(path)) System.Diagnostics.Process.Start(path);
        }

        private void lsvActions_DoubleClick(object sender, EventArgs e)
        {
            if (ReadOnly) return;
            if (lsvActions.SelectedItems.Count != 1) return;
            frmActiveItem form = new frmActiveItem();
            form.Adding = false;
            form.btnOK.Click += frmActiveItem_btnOK_Click;
            if ((lsvActions.SelectedItems[0].Tag as DBActive.Action).ActionDate == null)
                form.dtpDateAction.Checked = false;
            else
            {
                form.dtpDateAction.Checked = true;
                form.dtpDateAction.Value = (DateTime)(lsvActions.SelectedItems[0].Tag as DBActive.Action).ActionDate;
            }
            form.txtTheme.Text = (lsvActions.SelectedItems[0].Tag as DBActive.Action).Theme;
            form.txtNote.Text = (lsvActions.SelectedItems[0].Tag as DBActive.Action).Note;
            form.ShowDialog();
            return;
        }

        private void lsvReferenceFile_DoubleClick(object sender, EventArgs e)
        {
            if (lsvReferenceFile.SelectedItems.Count != 1) return;
            frmFile form = new frmFile();
            form.id = (lsvReferenceFile.SelectedItems[0].Tag as DBActive).id;
            form.Show();
        }

        private void cmsContext_Opening(object sender, CancelEventArgs e)
        {
            if (cmsContext.SourceControl.Name == lsvReferenceFile.Name)
                изменитьToolStripMenuItem.Enabled = false;
            else изменитьToolStripMenuItem.Enabled = true;
        }

        private void form_PostDoingStorageAdd(object sender, EventArgs e)
        {
            frmStorageEdit form = ((sender as Button).Parent as frmStorageEdit);
            DBActive.Storage storage = new DBActive.Storage(file, form.FullFileName, form.txtNote.Text);
            storage.Filename = ((sender as Button).Parent as frmStorageEdit).txtFileName.Text;
            storage.Save();
            imlPreview.Images.Clear();
            lsvStorage.Items.Clear();
            for (int i = 0; i < file.Storages.Length; i++)
            {
                if (file.Storages[i].isPicture && (!lsbListFoto.Items.Contains(file.Storages[i]))) lsbListFoto.Items.Add(file.Storages[i]);
                ListViewItem item = lsvStorage.Items.Add(file.Storages[i].Filename);
                item.SubItems.Add(file.Storages[i].Note);
                item.Tag = file.Storages[i];
                if (file.Storages[i].isPicture)
                {
                    imlPreview.Images.Add(file.Storages[i].Thumbnail);
                    item.ImageIndex = imlPreview.Images.Count - 1;
                }
            }
            ((sender as Button).Parent as frmStorageEdit).PostDoing -= form_PostDoingStorageAdd;
        }

        private void form_PostDoingStorageEdit(object sender, EventArgs e)
        {
            DBActive.Storage storage = (lsvStorage.SelectedItems[0].Tag as DBActive.Storage);
            storage.Note = ((sender as Button).Parent as frmStorageEdit).txtNote.Text;
            storage.Filename = ((sender as Button).Parent as frmStorageEdit).txtFileName.Text;
            storage.Save();
            ((sender as Button).Parent as frmStorageEdit).PostDoing -= form_PostDoingStorageEdit;
            imlPreview.Images.Clear();
            lsvStorage.Items.Clear();
            for (int i = 0; i < file.Storages.Length; i++)
            {
                if (file.Storages[i].isPicture && (!lsbListFoto.Items.Contains(file.Storages[i]))) lsbListFoto.Items.Add(file.Storages[i]);
                ListViewItem item = lsvStorage.Items.Add(file.Storages[i].Filename);
                item.SubItems.Add(file.Storages[i].Note);
                item.Tag = file.Storages[i];
                if (file.Storages[i].isPicture)
                {
                    imlPreview.Images.Add(file.Storages[i].Thumbnail);
                    item.ImageIndex = imlPreview.Images.Count - 1;
                }
            }
        }

        private void lsbStorage_DoubleClick(object sender, EventArgs e)
        {
            if (file == null) return;
            DBActive.Storage storage = (lsvStorage.SelectedItems[0].Tag as DBActive.Storage);
            string path = Path.Combine(Properties.Settings.Default.StartFolder, storage.Reference);
            if (File.Exists(path)) System.Diagnostics.Process.Start(path);
        }

        private void cmbRajonOfficial_DropDown(object sender, EventArgs e)
        {
            cmbRajonOfficial.Items.Clear();
            foreach (DBActive.RajonOfficial item in DBActive.RajonOfficial.LoadAll(file.Connection, file.Transaction, cmbRajonOfficial.Text))
            {
                cmbRajonOfficial.Items.Add(item);
            }

        }

        private void cmbRajonNonOfficial_DropDown(object sender, EventArgs e)
        {
            cmbRajonNonOfficial.Items.Clear();
            foreach (DBActive.RajonNonOfficial item in DBActive.RajonNonOfficial.LoadAll(file.Connection, file.Transaction, cmbRajonNonOfficial.Text))
            {
                cmbRajonNonOfficial.Items.Add(item);
            }
        }

        private void cmbParty_DropDown(object sender, EventArgs e)
        {
            cmbParty.Items.Clear();
            foreach (DBActive.Party item in DBActive.Party.LoadAll(file.Connection, file.Transaction, cmbParty.Text))
            {
                cmbParty.Items.Add(item);
            }

        }

        private void rtfNote_LinkClicked(object sender, LinkClickedEventArgs e)
        {
            System.Diagnostics.Process.Start(e.LinkText);
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            if (! ReadOnly)
	        {
                MessageBox.Show("Перед печатью необходимо сохранить изменения!");
                return;
	        }
            string folder = Application.StartupPath;
            if (Properties.Settings.Default.ShablonFolderOne != "") folder = Properties.Settings.Default.ShablonFolderOne;
            cmsReport.Items.Clear();            
            DirectoryInfo di = new DirectoryInfo(folder);
            foreach (FileInfo item in di.GetFiles("*.dot"))
            {
                if ((item.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden) continue;
                ToolStripItem menuReport = cmsReport.Items.Add(item.Name.Substring(0,item.Name.Length - item.Extension.Length));
                menuReport.Click += menuReport_Click;
            }
            cmsReport.Show(MousePosition);
        }

        void menuReport_Click(object sender, EventArgs e)
        {
            try
            {
                string folder = Application.StartupPath;
                if (Properties.Settings.Default.ShablonFolderOne != "") folder = Properties.Settings.Default.ShablonFolderOne;
                Type TWordApplication = Type.GetTypeFromProgID("Word.Application");
                dynamic wordApplication = Activator.CreateInstance(TWordApplication);
                wordApplication = wordApplication.Application;
                wordApplication.Documents.Add(Path.Combine(folder, (sender as ToolStripItem).Text + ".dot"));
                try
                {
                    wordApplication.Run("Init");
                }
                catch { }
                wordApplication.Run("Start", id);
                try
                {
                    wordApplication.Run("Done");
                }
                catch { }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }
}
